﻿#include"Stack.h"

//扩容
void StackDilatation(Stack* ps)
{
	assert(ps != NULL);
	STDataType* temp = (STDataType*)realloc(ps, sizeof(STDataType) * ps->_capacity * 2);
	if (temp == NULL)
	{
		printf("realloc fail!\n");
		exit(-1);
	}
	ps->_a = temp;
	ps->_capacity = ps->_capacity * 2;
}

// 初始化栈 
void StackInit(Stack* ps)
{
	STDataType* temp = (STDataType*)malloc(sizeof(STDataType) * 4);
	if (temp == NULL)
	{
		printf("malloc fail!\n");
		exit(-1);
	}
	ps->_a = temp;
	ps->_capacity = 4;
	ps->_top = 0;
}

// 入栈 
void StackPush(Stack* ps, STDataType data)
{
	assert(ps != NULL);
	if (ps->_capacity == ps->_top)
	{
		StackDilatation(ps);
	}
	ps->_a[ps->_top] = data;
	ps->_top++;
}

// 出栈 
void StackPop(Stack* ps)
{
	assert(ps != NULL);
	assert(ps->_top > 0);
	ps->_top--;
}

// 获取栈顶元素 
STDataType StackTop(Stack* ps)
{
	assert(ps != NULL);
	assert(ps->_top > 0);
	return ps->_a[ps->_top - 1];
}

// 获取栈中有效元素个数 
int StackSize(Stack* ps)
{
	assert(ps != NULL);
	return ps->_top;
}

// 检测栈是否为空，如果为空返回非零结果，如果不为空返回0 
int StackEmpty(Stack* ps)
{
	if (ps->_top == 0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

// 销毁栈 
void StackDestroy(Stack* ps)
{
	free(ps->_a);
	ps->_a = NULL;
}